import React from 'react';
import { Card, Button, Table, Space, Modal, Select, message, TableProps } from 'antd';
import { useParams } from 'react-router-dom';
import { type FormPanelObject, InputType } from 'lfun-bg-comp';
import _ from 'lodash';
import { YES_NO } from '@/constant/basicOptions';
import utils from '@/utils';
import FormPanelWrapper from '../../component/FormPanelWrapper';
import { TeaJobAppointmentSrv } from '@/service/teacher';
import {
  JOB_CATEGORY,
  JOB_LEVEL,
  PART_TIME_JOB_CATEGORY,
  PART_TIME_JOB_LEVEL,
  SCHOOL_POSITION,
} from '@/constant/teachOptions';
import { isPermissionOperate } from '@/component/permission-button';

const CustomTable: React.FC<{ value: any; onChange: Function }> = ({ value, onChange }) => {
  const defaultObj = {
    key: 'category',
    category: '',
    level: '',
  };
  if (value?.length === 0) {
    value = [{ ...defaultObj }];
  }

  const columns = [
    {
      title: '兼任岗位类别',
      dataIndex: 'category',
      key: 'category',
      render: (text, record, index) => (
        <Select
          style={{ width: '100%' }}
          options={JOB_CATEGORY}
          value={record.category}
          onChange={value => handleChange('category', index, value)}
        />
      ),
    },
    {
      title: '兼任岗位等级',
      dataIndex: 'level',
      key: 'level',
      render: (text, record, index) => (
        <Select
          style={{ width: '100%' }}
          options={JOB_LEVEL}
          value={record.level}
          onChange={value => handleChange('level', index, value)}
        />
      ),
    },
    {
      title: '操作',
      key: 'actions',
      //width: 200,
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record, index) => (
        <Space>
          <Button type="link" onClick={() => handleAdd(index)}>
            添加
          </Button>
          {index !== 0 && (
            <Button type="link" onClick={() => handleDelete(index)}>
              删除
            </Button>
          )}
        </Space>
      ),
    },
  ];

  const handleChange = (type, index, newValue) => {
    const newData = [...value];
    if (type === 'category') {
      newData[index] = { ...newData[index], category: newValue };
      onChange(newData);
    } else {
      newData[index] = { ...newData[index], level: newValue };
      onChange(newData);
    }
  };

  const handleAdd = index => {
    const newData = [...value];
    newData.splice(index + 1, 0, {
      key: `new${index}`,
      category: '请选择',
      level: '请选择',
    });
    onChange(newData);
  };

  const handleDelete = index => {
    const newData = [...value];
    newData.splice(index, 1);
    onChange(newData);
  };

  return (
    <div>
      <Table bordered dataSource={value} columns={columns} pagination={false} scroll={{ x: 'max-content' }} />
    </div>
  );
};

const PositionAppmt: React.FC<{ isEditPanel?: boolean }> = ({ isEditPanel = true }) => {
  const columns: TableProps['columns'] = [
    {
      title: '岗位类别',
      dataIndex: 'position_category',
      key: 'position_category',
      render: (text: any) => {
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(JOB_CATEGORY, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '岗位等级',
      dataIndex: 'position_level',
      key: 'position_level',
      render: (text: any) => {
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(JOB_LEVEL, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '聘任开始年月',
      dataIndex: 'appointment_start_date',
      key: 'appointment_start_date',
    },
    {
      title: '校级职务',
      dataIndex: 'school_level_position',
      key: 'school_level_position',
      render: (text: any) => {
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(SCHOOL_POSITION, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '任职开始年月',
      dataIndex: 'start_date',
      key: 'start_date',
    },
    {
      title: '是否兼任其他岗位',
      dataIndex: 'is_concurrent_other_positions',
      key: 'is_concurrent_other_positions',
      render: (text: any) => {
        return _.find(YES_NO, { value: Boolean(text) })?.label;
      },
    },
    {
      title: '兼任岗位类别',
      dataIndex: 'concurrent_position_category',
      key: 'concurrent_position_category',
      render: (val, record) => {
        let arr = [];
        if (record?.is_concurrent_other_positions) {
          if (_.isArray(record?.concurrent_position)) {
            arr = record.concurrent_position.map(
              item => _.find(PART_TIME_JOB_CATEGORY, { value: String(item.category) })?.label
            );
          }
        }
        return arr.join('、');
      },
    },
    {
      title: '兼任岗位等级',
      dataIndex: 'concurrent_position_registration',
      key: 'concurrent_position_registration',
      render: (val, record) => {
        let arr = [];
        if (record?.is_concurrent_other_positions) {
          if (_.isArray(record?.concurrent_position)) {
            arr = record.concurrent_position.map(item => item.level);
          }
        }
        return arr.join('、');
      },
    },
    {
      title: '操作',
      key: 'actions',
      //width: 200,
      fixed: 'right',
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => (
        <Space>
          {isEditPanel && (
            <Button type="link" onClick={() => handleEdit(record)}>
              编辑
            </Button>
          )}
          {isEditPanel && (
            <Button type="link" onClick={() => handleDelete(record)}>
              删除
            </Button>
          )}
          {!isEditPanel && (
            <Button type="link" onClick={() => handleEdit(record)}>
              查看
            </Button>
          )}
        </Space>
      ),
    },
  ];

  const list = [
    {
      title: '',
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      span: 12,
      inputs: [
        {
          label: '岗位类别',
          name: 'position_category',
          key: 'position_category',
          required: true,
          inputType: InputType.select,
          renderOption: JOB_CATEGORY,
        },
        {
          label: '岗位等级',
          name: 'position_level',
          key: 'position_level',
          required: true,
          inputType: InputType.cascader,
          renderOption: JOB_LEVEL,
        },
        {
          label: '聘任开始年月',
          name: 'appointment_start_date',
          key: 'appointment_start_date',
          required: true,
          inputType: InputType.date,
        },
        {
          label: '校级职务',
          name: 'school_level_position',
          key: 'school_level_position',
          required: true,
          inputType: InputType.select,
          renderOption: SCHOOL_POSITION,
        },
        {
          label: '任职开始年月',
          name: 'start_date',
          key: 'start_date',
          inputType: InputType.date,
        },
        {
          label: '是否兼任其他岗位',
          name: 'is_concurrent_other_positions',
          key: 'is_concurrent_other_positions',
          inputType: InputType.radio,
          renderOption: YES_NO,
        },
        {
          label: '',
          name: 'concurrent_position',
          key: 'concurrent_position',
          inputType: InputType.children,
          span: 24,
          props: {
            labelCol: { span: 0 },
            wrapperCol: { span: 24 },
          },
          children: <CustomTable value={[]} onChange={() => {}} />,
          hidden: (form: FormPanelObject) => {
            return !form.getFieldValue('is_concurrent_other_positions');
          },
        },
      ],
    },
  ];

  const { id: teacher_id } = useParams();
  const [currentRowId, setCurrentRowId] = React.useState(null);

  const [formValue, setFormValue] = React.useState({ concurrent_position: [], is_concurrent_other_positions: false });
  const [dataSource, setDataSource] = React.useState([]);

  React.useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    const res = await TeaJobAppointmentSrv.list({ teacher_id });
    console.log('🚀 ~ fetchData ~ res:', res);
    if (res.success) {
      setDataSource(res.data);
    }
  };

  // 新增 | 编辑
  const [showFormModel, setFormModel] = React.useState(false);
  const [isEdit, setIsEdit] = React.useState(false);

  const handleAdd = () => {
    setIsEdit(false);
    setFormValue({ concurrent_position: [], is_concurrent_other_positions: false });
    setFormModel(true);
  };

  const handleEdit = async (record: any) => {
    console.log('🚀 ~ handleEdit ~ record:', record);
    const { data } = await TeaJobAppointmentSrv.detail(record.teacher_job_appointments_id);

    const params = {
      ...data,
      position_category: data.position_category ? data.position_category?.split(',') : [],
      position_level: data.position_level ? data.position_level?.split(',') : [],
      school_level_position: data.school_level_position ? data.school_level_position?.split(',') : [],
    };
    console.log('🚀 ~ handleEdit ~ params:', params);

    setCurrentRowId(record.teacher_job_appointments_id);
    setFormValue(params);
    setIsEdit(true);
    setFormModel(true);
  };

  const handleDelete = (record: any) => {
    // content 按最字段内容为准，格式是否删除${证件类型}:${证件号码},姓名${姓名}的教师信息?
    Modal.confirm({
      title: '删除',
      content: `是否删除岗位类别: ${record.position_category} 相关信息?`,
      onOk: async () => {
        console.log('OK');
        const res = await TeaJobAppointmentSrv.delete(record.teacher_job_appointments_id);
        if (res.success) {
          message.success('删除成功');
          fetchData();
        }
      },
    });
  };

  const handleSave = async (formPanelObject: FormPanelObject) => {
    const values = formPanelObject.getFieldsValue();
    const params = {
      ...values,
      teacher_id,
    };
    params.appointment_start_date = utils.formatTime(params.appointment_start_date);
    params.start_date = utils.formatTime(params.start_date);
    //params.position_category = params.position_category?.join(',');
    params.position_level = params.position_level?.join(',');
    //params.school_level_position = params.school_level_position?.join(',');

    if (isEdit) {
      params.teacher_job_appointments_id = currentRowId;
    }
    console.log('🚀 ~ handleSave ~ params:', params);

    // 新增 | 编辑
    const server = isEdit ? 'update' : 'add';
    const res = await TeaJobAppointmentSrv[server](params);
    if (res.success) {
      message.success('保存成功');
      formPanelObject.resetFields();
      setFormModel(false);
      setCurrentRowId(null);
      fetchData();
    } else {
      formPanelObject.reVaildation(res);
    }
  };
  return (
    <Card title="岗位聘任" bordered={false}>
      {isEditPanel && (
        <Button type="primary" style={{ marginBottom: '20px' }} onClick={handleAdd}>
          新增
        </Button>
      )}
      <Table dataSource={dataSource} columns={columns} scroll={{ x: 'max-content' }} />
      <FormPanelWrapper
        title={isEdit ? (isEditPanel ? '岗位聘任编辑' : '岗位聘任详情') : '岗位聘任新增'}
        visible={showFormModel}
        formList={list}
        formValue={formValue}
        changeValue={setFormValue}
        onCancel={() => setFormModel(false)}
        onSave={handleSave}
        isEdit={isEditPanel}
      />
    </Card>
  );
};

PositionAppmt.defaultProps = {
  isEditPanel: true,
};

export default PositionAppmt;
